<?php
/**
 * Template
 *
 * Template is a class to handling templates.
 * It relates the template with code blocks ($code_block is the name to identify a dynamic space).
 * @Federico Silva <fsilva@adverit.com>
 * @version 1.0
 */
class Template extends DataObjectWed
{
    public $_dbTable = 'templates';
    public $_dbIndex = 'templateID';
    public $blocks = array(); 
    public $defaultProperties = array(); 
    public $clones = array();
    public $allBlocks = array(); // an array with all code blocks (identifier as array key and code as array value).
    public $template;
    public $_folder = "landings";
    public $_arFields = array('template'); // the name like the template folder.
    
    // ------------------------------------------------------------------------	
    /**
    * When you save the template you have to link code blocks
    * @return boolean
    */
    public function create()
    {
        if(parent::create())
        {    
            foreach($this->blocks as $property => $value)
            {
                if($property == 'sliders') continue;
                if($property == 'fields') continue;
                if(strpos($property, '_src_image')!==FALSE && (strpos($value, '--itemID--')!==FALSE || strpos($value, '/file_manager_item/')!==FALSE ))
                    {
                        if(strpos($value, '/file_manager_item/')!==FALSE )
                        {
                            $value =  $imageID = str_replace($GLOBALS['CONF']['url']['root'].'/upload/file_manager_item/', '', $value);
                            $value = "--itemID--".$value;
                        }

                        $this->saveImageID($property, $value);
                        continue;
                    }
                
                $sql = "INSERT INTO templates_blocks (templateID, code_block, code) values (".$this->templateID.", '".$property."', '".$this->txt2sql($value)."' )";
                $this->_mysqlQuery($sql, $this->_mysqlQueryResult);
            }
            return 1;
        }
        return 0;
    }        
    
    // ------------------------------------------------------------------------	
    
    /**
     * Update the template and code blocks.
     * @param integer|string $id
     * @return integer
     */
    public function update($id=null)
    {    
        if (parent::update($opt))
        {
            if(is_array($this->blocks))
            {           
                foreach ($this->blocks as $property => $value)
                {
                    if($property == 'sliders') continue;
                    if($property == 'fields') continue;
                    if(strpos($property, '_src_image')!==FALSE && (strpos($value, '--itemID--')!==FALSE || strpos($value, '/file_manager_item/')!==FALSE ))
                    {
                        if(strpos($value, '/file_manager_item/')!==FALSE )
                        {
                            $value =  $imageID = str_replace($GLOBALS['CONF']['url']['root'].'/upload/file_manager_item/', '', $value);
                            $value = "--itemID--".$value;
                        }

                        $this->saveImageID($property, $value);
                        continue;
                    }
                    
                    $sql = "REPLACE INTO templates_blocks (templateID, code_block, code) values (".$this->templateID.", '".$property."', '".$this->txt2sql($value)."' )";
                    $this->_mysqlQuery($sql, $this->_mysqlQueryResult);                    
                }
                return 1;
            }
        }
        return 0;
    }

    // ------------------------------------------------------------------------

    public function getTemplatePath($template_name = '')
    {
        $folder = $this->_folder != '' ? $this->_folder."/" : '';
        $template_name =  $template_name != '' ? $template_name."/" : $this->template."/";
        return $dir_template = DIR_ROOT ."/templates/".$folder.$template_name;
    }

    // ------------------------------------------------------------------------

    public function getTemplateUrl($template_name = '')
    {
        $folder = $this->_folder != '' ? $this->_folder."/" : '';
        $template_name =  $template_name != '' ? $template_name."/" : $this->template."/";
        return $dir_template = $GLOBALS['CONF']['url']['root']."/templates/".$folder.$template_name;
    }

    // ------------------------------------------------------------------------
    
    private function saveImageID($property, $value)
    {       
        $imageID = str_replace('--itemID--', '', $value);

        $image = new FileManagerItemImage();
        $image->setDBLink($this->_dbLink);
        $image->get($imageID);
        $image->userID_modified=$this->userID_modified;
        $image->save();        

        $value = $image->getImageUrl();
        $sql = "REPLACE INTO templates_blocks (templateID, file_image_id, code_block, code) values (".$this->templateID.",".$image->itemID.", '".$property."', '".$this->txt2sql($value)."' )";

        return $this->_mysqlQuery($sql, $this->_mysqlQueryResult);                    
    }

    // ------------------------------------------------------------------------
    
    /**
    * delete the code blocks  
    * @return boolean
    */
    public function delete($opt=null)
    {
        if (parent::delete($opt))
        {
            $this->deleteBlocks($opt);
            return 1;
        }
        return 0;
    }
    
    // ------------------------------------------------------------------------
    
    /**
    * getDefaultCodeValue is used to get default block values
    * params string;
    * params array;
    * @return string;
    */    
    
    public function getDefaultCodeValue($code_block)
    {
        preg_match("'(.*)_clone_(.*?)_'si", $code_block, $clone_num);                  
        $defaultCode = str_replace($clone_num[1]."_clone_".$clone_num[2], "1_clone_".$clone_num[2], $code_block);
        $defaultCodeValue = ($this->allBlocks[$code_block] != '' ? $this->allBlocks[$code_block] : ($this->blocks[$defaultCode] != '' ? $this->blocks[$defaultCode] : $this->defaultProperties[$defaultCode]));
        return $defaultCodeValue;
    }
    
    // ------------------------------------------------------------------------
    
    /**
    * getCodeBlocks is used to get all code blocks
    * @return array;
    */
    
    public function getCodeBlocks()
    {
        $arCodeBlocks = array();
        
        if($this->getID())
        {
            $sql = "SELECT code_block, code, file_image_id FROM templates_blocks WHERE templateID=".$this->getID()." ORDER BY blockID DESC ";
            $this->_mysqlQuery($sql, $this->_mysqlQueryResult);
            
            $hasTemplate = mysql_num_rows($this->_mysqlQueryResult);
        }
        
        if($hasTemplate)        
        {
            while ($row = mysql_fetch_assoc($this->_mysqlQueryResult))
            {       
                if(strpos($row['code_block'], '_clone_') !== FALSE)
                {
                    preg_match("'(.*)_clone_(.*?)_'si", $row['code_block'], $clone_num);        
                    $this->allBlocks[$row['code_block']] = $row['code'];                    
                    if($clone_num[1] == 1)
                    {
                        $arCodeBlocks[$row['code_block']] = $row['code'];   
                    }
                    else
                    {   
                        $ar_blocks["clone_".$clone_num[2]][$clone_num[1]][$row['code_block']] = $row['code'];
                    }   
                }
                else
                {
                     if(strpos($row['code_block'], 'slider_') !== FALSE) 
                     {
                        if(strpos($row['code_block'], '_description') !== FALSE) continue;
                        $arCodeBlocks['sliders'][] = array("slider_src_image"=>$row['code'], "code_block"=>$row['code_block']);
                     }
                     if(strpos($row['code_block'], 'field') !== FALSE) $arCodeBlocks['fields'][] = array("field"=>$row['code']);
                     $arCodeBlocks[$row['code_block']] = $row['code'];
                }
            }

            if(is_array($ar_blocks))
            {  
                $this->clones = $ar_blocks;
                foreach ($ar_blocks as $clone_id => $array)     
                {
                    foreach($array as $clone_num => $array_blocks)
                    {
                        $array_block_compare = array();
                        foreach ($array_blocks as $clone_code_block_compare => $clone_code_compare)
                        {
                            $array_block_compare[str_replace($clone_num."_clone", "1_clone", $clone_code_block_compare)] = '';
                        }
                        $array_default = array_diff_key($this->defaultProperties, $array_block_compare);
                                                
                        if(is_array($array_default) && count($array_default))
                        {
                            $array_blocks_default = array();
                            foreach ($array_default as $clone_code_block_compare => $clone_code_compare) 
                            {
                                $this->clones[$clone_id][$clone_num][str_replace("1_clone", $clone_num."_clone", $clone_code_block_compare)] = $clone_code_compare;
                            }
                        }
                    }
                }
            }
            $this->blocks = $arCodeBlocks;
        }
        else
        {
            $this->blocks = $this->defaultProperties;
            foreach($this->blocks as $key => $value)
            {   
                if(strpos($key, '_clone_') !== FALSE)
                {
                    preg_match("'(.*)_clone_(.*?)_'si", $key, $clone_num);        
                    $this->allBlocks[$key] = $value;     
                    $this->blocks['clone_'.$clone_num[1]] = '';
                }
            }
        }
        $this->allBlocks = array_merge($arCodeBlocks, $this->allBlocks);
        return 1;
    }
                  
    // ------------------------------------------------------------------------
    
    /**
    * getBlocks is used to get all code blocks, also the clones
    * @return boolean;
    */
    public function getClones()
    {
        if(count($this->clones))
        {
            foreach ($this->clones as $clone_id => $array)
            {
                preg_match("'<code id=\"".$clone_id."\">(.*?)</code>'si", $this->template, $match);
                $clonedHTML = $match[1];
            
                foreach ($array as $clone_num => $array_blocks)
                {   
                    $auxClonedHTML = '';
                    if($clone_num != '1')
                    {
                        $auxClonedHTML = $clonedHTML;
                        $auxClonedHTML = str_replace('class="clone_block"', 'class="cloned"', $auxClonedHTML);
                        $auxClonedHTML = str_replace("1_clone", $clone_num."_clone", $auxClonedHTML);
                    }           
                    
                    foreach($array_blocks as $clone_code_block => $clone_code)
                    {
                        $auxClonedHTML = str_replace("{{".$clone_code_block."}}", ($clone_code == '' || $clone_code == $this->defaultProperties[$clone_code_block]  ? $this->getDefaultCodeValue($clone_code_block) : $clone_code), $auxClonedHTML);
                    }
                    $this->blocks[$clone_id] .= $auxClonedHTML;
                }
            }
        }
    }
    
    // ------------------------------------------------------------------------    
    
    /**
    * delete the code blocks  
    * @return boolean
    */
    public function deleteBlocks($opt=null)
    {       
        if(is_array($opt))
        {
             $is_first = true;
             foreach($opt as $key => $value)
             {
                if($is_first) $condition.= " code_block='".$value."'";
                else $condition.= " OR code_block='".$value."'";
                
                $is_first = false;
             }
        }
        
        $sql = "SELECT * FROM templates_blocks WHERE templateID=".$this->getID().($condition !='' ? " AND (".$condition.")" : '');    
        $this->_mysqlQuery($sql, $this->_mysqlQueryResult);
        
        while($row = mysql_fetch_assoc($this->_mysqlQueryResult))
        {
            if($row['file_image_id'])
            {
                $fileManager = new FileManagerItemImage();
                $fileManager->setDBLink($this->_dbLink);
                $fileManager->get($row['file_image_id']);
                $fileManager->delete();
            }
                        
            $sqlDelete = "DELETE FROM templates_blocks WHERE blockID=".$row['blockID'];
            $this->_mysqlQuery($sqlDelete);
        }
        return 1;
    }
}

?>
